﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Xml.Linq;

namespace SC2parser.Function
{
    class SaveLoad
    {

        public static void Load(ref List<string> list, string filename)
        {
            try
            {
                using (Stream file = File.Open(filename, FileMode.Open))
                {

                    BinaryFormatter bf = new BinaryFormatter();
                    var obj = bf.Deserialize(file);


                    List<string> tempList = new List<string>();
                    tempList.AddRange(obj as List<string>);

                    list = tempList;

                }
            }
            catch (SerializationException)
            {
                MessageBox.Show("SERIALIZE EXCEPTION LOAD");
            }
            catch (FileNotFoundException)
            {

            }
        }

        public static void OnLoad(List<string> list)
        {

            List<string> files = new List<string>();

            files.AddRange(Directory.GetFiles(Application.StartupPath, "blacklist.dat"));

            if (files.Count() == 0)
            {
                list = new List<string>();
            }
            else if (files.Count() == 1)
            {
                SaveLoad.Load(ref list, files[0]);
            }
            else if (files.Count() > 1)
            {
                MessageBox.Show("More than one datafile present");
            }

        }

        public static void SaveList(List<string> list, string filename)
        {
            using (Stream file = File.Open(filename, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(file, list);
            }
        }


        public static void Save(List<string> list, string filename)
        {
            if (filename.Length == 0)
            {
                throw new ArgumentException();
            }
            try
            {
                SaveLoad.SaveList(list, filename);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Not a valid file");
            }
            catch (IOException)
            { Console.WriteLine("File being used by another proces"); }

        }


    }
}
